﻿namespace iFinance.Modules.Outgoings.ViewModels
{
    using System;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;
    using iFinance.IDAL;
    using iFinance.Infrastructure;
    using iFinance.Infrastructure.Models;
    using iFinance.Infrastructure.Services;
    using iFinance.Infrastructure.ViewModels;
    using iFinance.Modules.Outgoings.Events;
    using Microsoft.Practices.Prism.Commands;
    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.Prism.ViewModel;
    using Microsoft.Practices.Unity;

    /// <summary>
    /// 支出维护界面ViewModel
    /// </summary>
    public class OutgoingsMaintainViewModel : NotificationObject
    {
        #region Ctor

        public OutgoingsMaintainViewModel()
            : this(new OutgoingsItemViewModel())
        {
        }

        public OutgoingsMaintainViewModel(OutgoingsItemViewModel outgoingsItem)
        {
            OutgoingsItem = outgoingsItem;
            ConfirmCommand = new DelegateCommand(Confirm);
            CancelCommand = new DelegateCommand(Cancel);
            //初始化支出类型
            InitOutgoingsType();
            //初始化支出明细
            InitOutgoingsDetail();
        }

        #endregion

        #region 属性

        /// <summary>
        /// 支出项
        /// </summary>
        public OutgoingsItemViewModel OutgoingsItem { get; set; }

        private ManintainMode mode = ManintainMode.New;

        /// <summary>
        /// 维护模式
        /// </summary>
        public ManintainMode Mode
        {
            get { return this.mode; }
            set
            {
                if (this.mode != value)
                {
                    this.mode = value;
                    RaisePropertyChanged(() => this.Mode);
                }
            }
        }

        private OutgoingsTypeViewModel outgoingsTypes = null;

        /// <summary>
        /// 支出类别集合
        /// </summary>
        public OutgoingsTypeViewModel OutgoingsTypes
        {
            get { return this.outgoingsTypes; }
            set
            {
                if (this.outgoingsTypes != value)
                {
                    this.outgoingsTypes = value;
                    RaisePropertyChanged(() => this.OutgoingsTypes);
                }
            }
        }

        #endregion

        #region 命令

        #region ConfirmCommand

        private ICommand confirmCommand = null;

        /// <summary>
        /// 确认命令
        /// </summary>
        public ICommand ConfirmCommand
        {
            get { return this.confirmCommand; }
            set
            {
                if (this.confirmCommand != value)
                {
                    this.confirmCommand = value;
                    RaisePropertyChanged(() => this.ConfirmCommand);
                }
            }
        }

        /// <summary>
        /// 确认操作
        /// </summary>
        private void Confirm()
        {
            switch (Mode)
            {
                case ManintainMode.New:
                    AddOutgoings();
                    break;
                case ManintainMode.Modify:
                    ModifyOutgoings();
                    break;
            }
        }

        #endregion

        #region CancelCommand

        private ICommand cancelCommand = null;

        /// <summary>
        /// 取消命令
        /// </summary>
        public ICommand CancelCommand
        {
            get { return this.cancelCommand; }
            set
            {
                if (this.cancelCommand != value)
                {
                    this.cancelCommand = value;
                    RaisePropertyChanged(() => this.CancelCommand);
                }
            }
        }

        /// <summary>
        /// 取消操作
        /// </summary>
        private void Cancel()
        {
        }

        #endregion

        #endregion

        #region 方法

        /// <summary>
        /// 初始化支出列表
        /// </summary>
        private void InitOutgoingsType()
        {
            //获取支出类别列表
            var basicInfoService = UnityHelper.Container.Resolve<IBasicInfoService>();
            if (basicInfoService != null)
            {
                this.OutgoingsTypes = basicInfoService.GetAllOutgingsType();
                // 初始化支出类别选择
                if (this.OutgoingsItem != null)
                {
                    if (this.OutgoingsItem.OutgoingsType != null)
                    {
                        var outgoingType = this.OutgoingsTypes.List.FirstOrDefault(type => { return type.ID.Equals(this.OutgoingsItem.OutgoingsType.ID); });
                        this.OutgoingsItem.OutgoingsType = outgoingType;
                    }

                    if (this.OutgoingsItem.OutgoingsType == null && this.OutgoingsTypes != null && this.OutgoingsTypes.List.Count > 0)
                    {
                        this.OutgoingsItem.OutgoingsType = this.OutgoingsTypes.List[0];
                    }
                }
            }
        }

        /// <summary>
        /// 初始化支出明细项
        /// </summary>
        private void InitOutgoingsDetail()
        {
            //如果明细项没有加载过，则加载
            if (this.OutgoingsItem != null && !this.OutgoingsItem.IsDetailLoaded)
            {
                this.OutgoingsItem.IsDetailLoaded = true;

                if (this.OutgoingsItem.OutgoingsDetail == null)
                {
                    this.OutgoingsItem.OutgoingsDetail = new OutgoingsDetailViewModel();
                }

                // 加载明细
                var dao = UnityHelper.Container.Resolve<IOutgoingsDAO>();
                if (dao != null)
                {
                    var details = dao.QueryOutgoingsDetail(this.OutgoingsItem.RealData.ID);
                    if (details != null)
                    {
                        foreach (var detail in details)
                        {
                            this.OutgoingsItem.OutgoingsDetail.AddDetailItem(new OutgoingsDetailItemViewModel(detail));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 添加支出项
        /// </summary>
        private void AddOutgoings()
        {
            var item = OutgoingsItem.RealData;
            item.LastModifyDate = DateTime.Now;
            OutgoingsItem.TotalAmount = OutgoingsItem.OutgoingsDetail.TotalAmount;
            item.TotalAmount = OutgoingsItem.TotalAmount;
            if (OutgoingsItem.OutgoingsType != null)
            {
                item.TypeID = OutgoingsItem.OutgoingsType.ID;
            }
            else
            {
                //TODO 如果支出类型不存在，则添加新的支出类型并设置TypeID
            }
            //保存支出项，并获取ID
            var dao = UnityHelper.Container.Resolve<IOutgoingsDAO>();
            if (dao != null)
            {
                item.ID = dao.AddOutgoings(item);
                //TODO 暂不考虑保存失败的情况
            }
            else
            {
                MessageBox.Show("保存失败", "提示", MessageBoxButton.OK);
                return;
            }
            //保存支出明细项
            if (OutgoingsItem.OutgoingsDetail.List != null)
            {
                foreach (var detailItem in OutgoingsItem.OutgoingsDetail.List)
                {
                    detailItem.RealData.OutgoingsID = item.ID;
                    dao.AddOutgoingsDetail(detailItem.RealData);
                }
            }
            //发布添加完成的事件
            UnityHelper.Container.Resolve<IEventAggregator>().GetEvent<OutgoingsAddedEvent>().Publish(OutgoingsItem);
        }

        /// <summary>
        /// 修改支出项
        /// </summary>
        private void ModifyOutgoings()
        {
            var item = OutgoingsItem.RealData;
            item.LastModifyDate = DateTime.Now;
            OutgoingsItem.TotalAmount = OutgoingsItem.OutgoingsDetail.TotalAmount;
            item.TotalAmount = OutgoingsItem.TotalAmount;
            if (OutgoingsItem.OutgoingsType != null)
            {
                item.TypeID = OutgoingsItem.OutgoingsType.ID;
            }
            else
            {
                //TODO 如果支出类型不存在，则添加新的支出类型并设置TypeID
            }
            //保存支出项，并获取ID
            var dao = UnityHelper.Container.Resolve<IOutgoingsDAO>();
            bool isSuccess = false;
            if (dao != null)
            {
                isSuccess = dao.UpdateOutgoings(item);
            }

            if(!isSuccess)
            {
                MessageBox.Show("修改失败", "提示", MessageBoxButton.OK);
                return;
            }

            //保存支出明细项
            if (OutgoingsItem.OutgoingsDetail.List != null)
            {
                foreach (var detailItem in OutgoingsItem.OutgoingsDetail.List)
                {
                    //不相同为新增
                    if (detailItem.RealData.OutgoingsID != item.ID)
                    {
                        detailItem.RealData.OutgoingsID = item.ID;
                        dao.AddOutgoingsDetail(detailItem.RealData);
                    }
                    //相同为更新
                    else
                    {
                        dao.UpdateOutgoingsDetail(detailItem.RealData);
                    }
                }
            }
        }

        #endregion
    }
}